using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Hotran.SaveSystem
{
    public class SavableEntity : MonoBehaviour, IIdentifiable
    {
        [SerializeField]
        private string id = string.Empty;

        public string Id => id;

        [ContextMenu("Generate ID")]
        public void GenerateId()
        {
#if UNITY_EDITOR
            id = System.Guid.NewGuid().ToString();
            UnityEditor.EditorUtility.SetDirty(this);
            Debug.Log($"Id generated for {name}");
#endif
        }

        private void Start()
        {
            if (id == string.Empty)
                Debug.LogError("id is empty!", gameObject);
        }

        /// <summary>
        /// ���浱ǰ�����״̬
        /// </summary>
        /// <returns></returns>
        public object SaveState()
        {
            var state = new Dictionary<string, object>();
            var savables = GetComponents<ISavable>();

            //���������Ͽɱ��������״̬
            foreach (var savable in savables)
            {
                state[savable.GetType().ToString()] = savable.Save();
            }

            return state;
        }

        /// <summary>
        /// �ָ���ǰ�����״̬
        /// </summary>
        /// <param name="data"></param>
        public void RestoreState(object data)
        {
            var state = data as Dictionary<string, object>;
            if (state == null)
            {
                Debug.LogError($"Invalid load data for {name}");
                return;
            }

            foreach (var savable in GetComponents<ISavable>())
            {
                string typeName = savable.GetType().ToString();

                if (state.TryGetValue(typeName, out object value))
                {
                    savable.Load(value);
                }
            }
        }
    }
}